<template>
  <div class="label-fees-detail merak-container-has-search">
    <SearchBar ref="searchRef" v-model="searchForm" closeEnter @search-event="data => handleSearchToTableParams(data.params)">
      <template #footer>
        <el-button v-auth="{ authArr: props.auth, key: 'add' }" type="primary" @click="handleEdit()">
          {{ $t("marking_labelFees.add_payment") }}
        </el-button>
      </template>
      <template #searchForm>
        <div class="modal-content">
          <div class="modal-title"></div>
          <div class="modal—body">
            <el-scrollbar class="search_from_scrollbar">
              <div class="scrollbar-content">
                <SelectedParams v-model="searchForm" />
                <el-form label-position="top">
                  <el-row :gutter="40">
                    <el-col :span="props.span">
                      <el-form-item prop="payment_date" :label="searchForm.payment_date.label">
                        <el-date-picker
                          v-model="searchForm.payment_date.value"
                          class="qf_date"
                          type="daterange"
                          value-format="YYYY-MM-DD"
                          :format="format"
                          :range-separator="$t('merak.rangto')"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="payment_amount" :label="searchForm.payment_amount.label">
                        <el-input v-model="searchForm.payment_amount.value" v-number:4 class="qf_input" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="payment_type" :label="searchForm.payment_type.label">
                        <el-select v-model="searchForm.payment_type.value" class="qf_select">
                          <el-option
                            v-for="option in searchForm.payment_type.options"
                            :value="option.value"
                            :label="option.label"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="payer" :label="searchForm.payer.label">
                        <el-select v-model="searchForm.payer.value" class="qf_select">
                          <el-option v-for="option in searchForm.payer.options" :value="option.value" :label="option.label" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="payee" :label="searchForm.payee.label">
                        <el-select v-model="searchForm.payee.value" class="qf_select">
                          <el-option v-for="option in searchForm.payee.options" :value="option.value" :label="option.label" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="operator" :label="searchForm.operator.label">
                        <el-select v-model="searchForm.operator.value" class="qf_select">
                          <el-option v-for="option in searchForm.operator.options" :value="option.value" :label="option.label" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="pay_factory_id" :label="searchForm.pay_factory_id.label">
                        <el-select v-model="searchForm.pay_factory_id.value" class="qf_select">
                          <el-option
                            v-for="option in searchForm.pay_factory_id.options"
                            :value="option.value"
                            :label="option.label"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="remark" :label="searchForm.remark.label">
                        <el-input v-model="searchForm.remark.value" class="qf_input" type="textarea" :rows="2" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </el-scrollbar>
          </div>
          <div class="modal-footer">
            <el-button @click="handleReset">{{ $t("merak.reset") }}</el-button>
            <el-button type="primary" @click="handleSearch">{{ $t("merak.search") }}</el-button>
            <el-button type="primary" plain @click="searchRef?.showPlanModal">
              {{ $t("merak.save_search_scheme") }}
            </el-button>
          </div>
        </div>
      </template>
    </SearchBar>
    <div class="merak-table-wrapper">
      <MerakXTable
        ref="tableRef"
        v-bind="tableState"
        :column-type="tableColumnType"
        :queryColumns="handleQueryColumns"
        :queryData="handleQueryData"
      >
        <template #custom_handle="{ row }">
          <el-button v-auth="{ authArr: props.auth, key: 'edit' }" type="primary" link @click="handleEdit(row)">
            {{ $t("merak.edit") }}
          </el-button>
          <el-button v-auth="{ authArr: props.auth, key: 'delete' }" type="danger" link @click="handleDelete(row)">
            {{ $t("merak.delete") }}
          </el-button>
        </template>
      </MerakXTable>
    </div>
    <AddForm
      ref="addRef"
      :currency="props.currency"
      :data="editData"
      :optionGroup="optionGroup"
      @close="saved => saved && tableRef?.reloadData()"
    />
  </div>
</template>

<script setup lang="ts">
import type { LabelFeesType, OptionType } from "../index";

import type { UserAuthType } from "@/api/modules/user";

import { getCurrentInstance, ref, reactive, onMounted } from "vue";

import { useRoute } from "vue-router";

import useDateFormat from "@/hooks/useDateFormat";

import useLoading from "@/hooks/useLoading";

import {
  ElButton,
  ElScrollbar,
  ElForm,
  ElFormItem,
  ElRow,
  ElCol,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElMessage
} from "element-plus";

import SearchBar from "@/components/SearchBar/index.vue";

import SelectedParams from "@/components/SearchBar/components/selectedParams.vue";

import MerakXTable, { MerakXTableInstance, MerakXTableProps } from "@/components/MerakXTable";

import AddForm from "./AddForm.vue";

import { ResultEnum } from "@/enums/httpEnum";
import { getPaymentOptions, getPaymentColumns, getPaymentData, deletePayment } from "@/api/modules/markingManagement/labelFees";

import { confirmWarningMsg } from "@/utils/messageUtils";
import { computed } from "vue";

const props = defineProps<{
  currency: LabelFeesType;
  auth: UserAuthType;
  span: number;
}>();

const currentInstance = getCurrentInstance();

const route = useRoute();

const { format } = useDateFormat();

const { queueId, queueLoading } = useLoading();

const tableRef = ref<MerakXTableInstance>();

const searchRef = ref<InstanceType<typeof SearchBar>>();

const addRef = ref<InstanceType<typeof AddForm>>();

// 编辑行数据
const editData = ref<Record<string, any> | null>();

// 缴费下拉选项集合
const optionGroup = ref<Record<string, OptionType[]>>({});

// 高级搜索表单数据
const searchForm = reactive<
  Record<
    string,
    {
      type: string;
      label?: string;
      value?: any;
      options?: OptionType[];
    }
  >
>({
  payment_date: {
    type: "dateTimeRange",
    label: currentInstance?.proxy?.$t("marking_labelFees.payment_date")
  },
  payment_amount: {
    type: "input",
    label: currentInstance?.proxy?.$t("marking_labelFees.payment_amount")
  },
  payment_type: {
    type: "select",
    label: currentInstance?.proxy?.$t("marking_labelFees.payment_type")
  },
  payer: {
    type: "select",
    label: currentInstance?.proxy?.$t("marking_labelFees.payer")
  },
  payee: {
    type: "select",
    label: currentInstance?.proxy?.$t("marking_labelFees.payee")
  },
  operator: {
    type: "select",
    label: currentInstance?.proxy?.$t("marking_labelFees.operator")
  },
  pay_factory_id: {
    type: "select",
    label: currentInstance?.proxy?.$t("marking_labelFees.pay_factory_id")
  },
  remark: {
    type: "input",
    label: currentInstance?.proxy?.$t("marking_labelFees.remark")
  }
});

const tableState = reactive<MerakXTableProps>({
  columnsByStore: [],
  toolbar: ["refresh", "export"],
  params: {}
});

const tableColumnType = computed<MerakXTableProps["columnType"]>(() => {
  if (props.auth?.edit?.show && props.auth?.delete?.show) {
    return [{ type: "handle", width: 120, slot: "custom_handle" }];
  }
  return;
});

// 请求列表头
const handleQueryColumns: MerakXTableProps["queryColumns"] = async () => {
  const params: Record<string, any> = {
    supplier_id: route.query.id,
    currency: props.currency
  };
  return getPaymentColumns(params, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      tableState.columnsByStore = JSON.parse(JSON.stringify(data.columns));
      searchRef.value?.getPlanList(data.table_id);
      return {
        ...data,
        columns: [...(data.columns ?? [])].map(col => {
          switch (col.field) {
            case "operator":
            case "payment_type":
            case "pay_factory_id":
              col.slots = { default: ({ row }) => row[`${col.field}_txt`] };
              break;
            default:
              break;
          }
          return { ...col };
        })
      };
    }
  });
};

// 请求列表数据
const handleQueryData: MerakXTableProps["queryData"] = async ({ page, from }) => {
  const params: Record<string, any> = {
    supplier_id: route.query.id,
    currency: props.currency
  };
  if (!!page) {
    Object.assign(params, page);
  }
  if (!!from) {
    Object.assign(params, from);
  }
  return getPaymentData(params, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      return { ...data.table_data };
    }
  });
};

// 重置高级搜索
const handleReset = () => {
  Object.values(searchForm).forEach(item => delete item.value);
};

// 高级搜索赋值到表格
const handleSearchToTableParams = (params: Record<string, any>) => {
  if (Array.isArray(params.payment_date)) {
    const [payment_date_start, payment_date_end] = params.payment_date;
    Object.assign(params, { payment_date_start, payment_date_end });
    delete params.payment_date;
  }
  tableState.params = { ...params };
};

// 高级搜索
const handleSearch = () => {
  const params: Record<string, any> = searchRef.value?.formParams("value") ?? {};

  handleSearchToTableParams(params);

  searchRef.value?.clear();
  searchRef.value?.modalHide();
};

// 编辑
const handleEdit = (row?: Record<string, any>) => {
  editData.value = !!row ? { ...row } : null;
  addRef.value?.open();
};

// 删除
const handleDelete = (row: Record<string, any>) => {
  confirmWarningMsg({
    msg: "确认删除缴费明细",
    callback: (status: string) => {
      if (status === "confirm") {
        const params: Record<string, any> = {
          supplier_id: route.query.id,
          currency: props.currency,
          payment_record_id: row.payment_record_id
        };
        deletePayment(params).then(({ code, message }) => {
          if (code == ResultEnum.SUCCESS) {
            tableRef.value?.reloadData();
            ElMessage.success("删除成功");
          } else {
            const msg = typeof message === "object" ? Object.values(message)?.[0] : message;
            ElMessage.error(msg);
          }
        });
      }
    }
  });
};

onMounted(() => {
  getPaymentOptions({
    supplier_id: route.query.id as string,
    currency: props.currency
  }).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      searchForm.payment_type.options = [...(data.payment_type ?? [])];
      searchForm.payer.options = [...(data.payer ?? [])];
      searchForm.payee.options = [...(data.payee ?? [])];
      searchForm.operator.options = [...(data.operator ?? [])];
      searchForm.pay_factory_id.options = [...(data.pay_factory_id ?? [])];
      optionGroup.value = { ...(data ?? {}) };
    }
  });
});
</script>

<style scoped lang="scss">
.scrollbar-content {
  :deep(.el-form-item__content > *) {
    width: 100%;
  }
}
</style>
